//
//  BaseDataManager.m
//  OrderSeat
//
//  Created by 王威 on 14-2-20.
//  Copyright (c) 2014年 wangwei. All rights reserved.
//

#import "BaseDataManager.h"

#define CAIXI_TAG 1001
#define XIANQU_TAG 1002
#define ORDER_TAG  1003
#define JULI_TAG   1004
#define DATA_VERSION_TAG 1005
#define FETCH_CITY_TAG 1006

@implementation BaseDataManager

static BaseDataManager* dataManager = nil;

+ (id)sharedInstance
{
	@synchronized(self) {
        if (dataManager == nil)
			dataManager = [[self alloc] init];
	}
	return dataManager;
}

- (void)startDownLoad
{
    if (![AppSetting cityId] || [[AppSetting cityId] length] == 0) {
        [self fetchCurrentCity];
    }
}

- (void)startDownLoad2
{
    [self fetchCommDatas];
}

- (void)fetchCurrentCity
{
    NSString *url = [NSString stringWithFormat:API_FETCH_CITY, [AppSetting longitude],[AppSetting latitude]];
    [self get:url tag:FETCH_CITY_TAG];
}

- (void)fetchCommDatas
{
    [SVProgressHUD show];
    count = 0; responseCount = 0;
    [[DbManager sharedManager] clearMenuList];
    
    NSString *xianquURL = [NSString stringWithFormat:API_XIANQU, [AppSetting cityId]];
    
    [self get:API_CAIXI tag:CAIXI_TAG];
    [self get:xianquURL tag:XIANQU_TAG];
    [self get:API_ORDER tag:ORDER_TAG];
    [self get:API_DISTANCE tag:JULI_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == XIANQU_TAG) {
        NSArray *areas = [json objectForKey:@"dxianqu"];
        [[DbManager sharedManager] insertAreas:areas];
        count++;responseCount++;
    }
    
    if (request.tag == CAIXI_TAG) {
        NSArray *cuisines = [json objectForKey:@"dcaixi"];
        [[DbManager sharedManager] insertCuisines:cuisines];
        count++;responseCount++;
    }
    
    if (request.tag == ORDER_TAG) {
        NSArray *orders = [json objectForKey:@"paixu"];
        [[DbManager sharedManager] insertOrders:orders];
        count++;responseCount++;
    }
    
    if (request.tag == JULI_TAG) {
        NSArray *distances = [json objectForKey:@"distance"];
        [[DbManager sharedManager] insertDistances:distances];
        count++;responseCount++;
    }
    
    if(request.tag == FETCH_CITY_TAG) {
        //{"error_code":0,"city":{"id":"1","name":"兰州市"}}
        NSDictionary *city = [json objectForKey:@"city"];
        NSString *cityId = [city objectForKey:@"id"];
        NSString *cityName = [city objectForKey:@"name"];
        
        [AppSetting setCityId:cityId];
        [AppSetting setCityName:cityName];
        
        [self fetchCommDatas];
    }
    
    if (responseCount == 4 && count == 4){
        [SVProgressHUD dismissWithSuccess:@"数据加载完成"];
//        [AppSetting setDataVersion:_dataVersion];
    }
}

@end
